#include <sys/types.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "protocol.h"

int getconnection(char * hostname);
void startremote();
void catch_int(int signo);

int sockfd;

int main(int argc, char * argv[]) 
{

	if (argc != 2) {
		fprintf(stderr, "Usage: ./ground <hostname>\n");
		exit(EXIT_FAILURE);
	}

	signal(SIGINT, catch_int);
	sockfd = getconnection(argv[1]);
	startremote();

	return EXIT_SUCCESS;
}

int getconnection(char * hostname)
{
	struct sockaddr_in serveraddr;
	struct hostent * host;
	int sockfd;
	
	host = gethostbyname (hostname);
	if (host == NULL) {
		perror("p_gethostbyname:");
		herror("h_gethostbyname:");
		exit (EXIT_FAILURE);
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		perror ("socket:");
		exit (EXIT_FAILURE);
	}

	memset(&serveraddr, 0, sizeof (struct sockaddr_in));
	memcpy(& (serveraddr.sin_addr), host->h_addr, host->h_length);
	serveraddr.sin_family = host->h_addrtype;
	serveraddr.sin_port = htons (PORT);
	if (connect(sockfd, (struct sockaddr*) & serveraddr, sizeof(struct sockaddr))) {
		perror ("connect:");
		exit (EXIT_FAILURE);
	}
	fprintf(stderr, "After connect\n");

	return sockfd;
}

void startremote()
{
	char buf[4096];
	int pid;

	pid = fork();
	switch(pid) {
	case -1:
		perror("fork:");
		exit(EXIT_FAILURE);
	case 0:
		while (1) {
			memset(buf, 0, 4096);
			if (read(sockfd, buf, 4096) <= 0) {
				exit(EXIT_FAILURE);
			}
			fprintf(stderr, "%s", buf);
		}
		break;
	default:
		while (1) {
			memset(buf, 0, 4096);
			if (fgets(buf, 4096, stdin))	
				write (sockfd, buf, strlen(buf));
			if (!strncmp("timelapse", buf, strlen("timelapse"))) {
				memset(buf, 0, 4096);
				fgets(buf, 4096, stdin);
				while (strcmp("stop\n", buf)) {
					fprintf(stdout, "Enter stop to quit timelapse: ");
					memset(buf, 0, 4096);
					fgets(buf, 4096, stdin);
				}
				write(sockfd, buf, strlen(buf));
			}
			else if (!strcmp("q\n", buf)) {
				close(sockfd);
				exit(0);
			}
		}
	}
}

void catch_int(int signo)
{
	write(sockfd, "stop\n", 5);
	usleep(1000);
	write(sockfd, "q\n", 2);	
	close(sockfd);
	exit(0);
}
